package collection.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQueueDe {


    public static void main(String[] args) throws InterruptedException {

        BlockingQueue<De> delayqueue = new DelayQueue<>();


        long now = System.currentTimeMillis();
        delayqueue.put(new De(now + 3000));
        delayqueue.put(new De(now + 4000));
        delayqueue.put(new De(now + 6000));
        delayqueue.put(new De(now + 1000));

//
//        delayqueue.put(new De(now - 3000));
//        delayqueue.put(new De(now - 4000));
//        delayqueue.put(new De(now - 6000));
//        delayqueue.put(new De(now - 1000));

        System.out.println(delayqueue);

        for (int i = 0; i < 45; i++) {
            System.out.println(i + "  " + delayqueue.take());
        }


    }

    static class De implements Delayed {


        long time = System.currentTimeMillis();

        public De(long time) {
            this.time = time;
        }

        @Override
        public int compareTo(Delayed o) {
            if (this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS))
                return -1;
            else if (this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS))
                return 1;
            else
                return 0;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(time - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }

        @Override
        public String toString() {
            return "" + time;
        }
    }

}
